package com.jar.exercise.多线程.AQS.reentrantreadwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
    private final Lock READLOCK = lock.readLock();
    private final Lock WRITELOCK = lock.writeLock();

    private void read() {
        READLOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":获取读锁");
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName() + ":释放读锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            READLOCK.unlock();
        }
    }

    private void write() {
        WRITELOCK.lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":获取写锁");
            TimeUnit.SECONDS.sleep(3);
            System.out.println(Thread.currentThread().getName() + ":释放写锁");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            WRITELOCK.unlock();
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        // 第一种情况：两个线程都是读锁（不会阻塞）
        //  new Thread(main::read,"线程A").start();
        //  new Thread(main::read,"线程B").start();

        // 第二种情况：两个线程都是写锁（阻塞）
        //new Thread(main::write,"线程A").start();
        //new Thread(main::write,"线程B").start();

        // 第三种情况：读写锁都有（都阻塞）
        new Thread(main::read, "线程A").start();
        new Thread(main::write, "线程B").start();
    }
}
